const User = require('../models/User')
// 响应的json数据
const responseData = {
  code: 200,
  msg: 'success',
  data: {}
}

// 用户注册
exports.register = (req, res) => {
  const username = req.body.username
  const password = req.body.password;
  if(!username) {
    responseData.code = 500
    responseData.msg = '用户名不能为空'
    responseData.data = {}
    res.json(responseData)
    return;
  }
  if(!password) {
    responseData.code = 500
    responseData.msg = '密码不能为空'
    responseData.data = {}
    res.json(responseData)
    return;
  }
  User.findOne({
    username: username
  }).then((userInfo) => {
    if (userInfo) {
      console.error('用户已存在')
      responseData.code = 202
      responseData.msg = '用户已存在'
      responseData.data = {}
      return
    } else {
      const user = new User({
        username: username,
        password: password
      })
      return user.save()
    }
  }).then(newUserInfo => {
    if(newUserInfo) {
      responseData.code = 200
      responseData.msg = '注册成功'
      responseData.data = {}
    }
    res.json(responseData)
    return
  }).catch((err) => {
    console.log(err);
    responseData.code = 500
    responseData.msg = '服务出现异常'
    responseData.data = {}
    res.json(responseData)
    return
  })
}

// 用户登录
exports.login = (req, res) => {
  const username = req.body.username
  const password = req.body.password
  if(!username) {
    responseData.code = 500
    responseData.msg = '用户名不能为空'
    responseData.data = {}
    res.json(responseData)
    return;
  }
  if(!password) {
    responseData.code = 500
    responseData.msg = '密码不能为空'
    responseData.data = {}
    res.json(responseData)
    return;
  }
  User.findOne({
    username: username,
    password: password
  }).then((userInfo)=>{
    if(userInfo) {
      responseData.code = 200
      responseData.msg = '登录成功'
      responseData.data = {
        _id: userInfo._id,
        username: userInfo.username,
        date: userInfo.date
      }
      res.json(responseData)
      return
    } else {
      responseData.code = 500
      responseData.msg = '用户名或密码错误'
      responseData.data = {}
      res.json(responseData)
      return
    }
  })
}


// 用户注销
exports.logout = (req, res) => {

}
